package service

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/google/uuid"
	"log"
	"math/rand"
	"strconv"
	"time"
	"video-srv/basic/config"
	__ "video-srv/basic/proto"
	"video-srv/handler/model"
	"video-srv/pkg"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedUserServer
}
type Task struct {
	Phone string
	Code  string
}

// SayHello implements helloworld.GreeterServer
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	//phoneRegxp := `^[1-3]\d{9}$`
	//matchString, _ := regexp.MatchString(phoneRegxp, in.Phone)
	//if !matchString {
	//	return nil, fmt.Errorf("手机号码验证错误")
	//}
	result, _ := config.Rdb.Get(config.Ctx, "sendCode"+in.Phone).Result()
	if result == "3" {
		return nil, fmt.Errorf("该验证码只能一分钟发三次")
	}
	code := rand.Intn(9000) + 100
	//sms := pkg.SmsFoktory.AliSms("aliyun")
	//sendSms, _ := sms.SendSms(in.Phone, strconv.Itoa(code))
	//if *sendSms.Body.Code != "OK" {
	//	return nil, fmt.Errorf(*sendSms.Body.Message)
	//}
	config.Rdb.Set(config.Ctx, "sendSms"+in.Phone, code, time.Minute*5)
	incr := config.Rdb.Incr(config.Ctx, "sendCode"+in.Phone)
	if incr.Val() == 1 {
		config.Rdb.Expire(config.Ctx, "sendCode"+in.Phone, time.Minute*1)
	}
	task := &Task{
		Phone: in.Phone,
		Code:  strconv.Itoa(code),
	}
	marshal, err := json.Marshal(task)
	if err != nil {
		return nil, err
	}
	simple := pkg.NewRabbitMQSimple(string(marshal))
	publishSimple, err := simple.PublishSimple("phone 发送成功")
	if err != nil {
		return nil, err
	}
	log.Println(publishSimple)
	return &__.SendSmsResp{}, nil
}
func (s *Server) GetPhoneByPhone(_ context.Context, in *__.GetPhoneByPhoneReq) (*__.GetPhoneByPhoneResp, error) {
	var user model.User
	if err := user.GetPhoneByPhone(config.DB, in.Phone); err != nil {
		return nil, err
	}
	return &__.GetPhoneByPhoneResp{
		Phone:    user.Phone,
		Password: user.Password,
		UserId:   int64(user.ID),
	}, nil
}
func (s *Server) CreateUser(_ context.Context, in *__.CreateUserReq) (*__.CreateUserResp, error) {

	user := model.User{
		Phone:    in.Phone,
		Password: pkg.Md5(in.Password),
	}
	result, _ := config.Rdb.Get(config.Ctx, "sendSms"+in.Phone).Result()
	if result != in.Code {
		return nil, fmt.Errorf("验证码失效")
	}
	if err := user.CreateUser(config.DB); err != nil {
		return nil, err
	}
	return &__.CreateUserResp{
		UserId: int64(user.ID),
	}, nil
}
func (s *Server) CreateVideo(_ context.Context, in *__.CreateVideoReq) (*__.CreateVideoResp, error) {
	video := model.Video{
		UserId:       in.UserId,
		Title:        in.Title,
		Dsc:          in.Desc,
		UploadUrl:    in.UploadUrl,
		LikeCount:    in.LikeCount,
		CollectCount: in.CollectCount,
		CommentCount: in.CommentCount,
		Hot:          in.Hot,
		PayCount:     in.PayCount,
		IsVip:        in.IsVip,
		TagId:        in.TagId,
		TypeId:       in.TypeId,
		Status:       in.Status,
	}
	if video.Status == 1 {
		return nil, fmt.Errorf("该视频已下架")
	}
	if err := video.VideoAdd(config.DB); err != nil {
		return nil, err
	}

	return &__.CreateVideoResp{
		VideoId: int64(video.ID),
	}, nil
}
func (s *Server) VideoCheck(_ context.Context, in *__.VideoCheckReq) (*__.VideoCheckResp, error) {
	var videos model.Video
	if err := videos.VideoUpdate(config.DB, in.Id, in.Status); err != nil {
		return nil, err
	}
	return &__.VideoCheckResp{
		VideoId: in.Id,
	}, nil
}
func (s *Server) CreateType(_ context.Context, in *__.CreateTypeReq) (*__.CreateTypeResp, error) {
	t := model.Type{
		TypeName: in.TypeName,
		Pid:      in.PId,
	}
	if err := t.TypeAdd(config.DB); err != nil {
		return nil, err
	}
	return &__.CreateTypeResp{
		TypeId: int64(t.ID),
	}, nil
}
func (s *Server) CreateTag(_ context.Context, in *__.CreateTagReq) (*__.CreateTagResp, error) {
	tag := model.Tag{
		TagName:  in.TagName,
		TageType: in.TagType,
	}
	if err := tag.TagAdd(config.DB); err != nil {
		return nil, err
	}
	return &__.CreateTagResp{
		TagId: int64(tag.ID),
	}, nil
}
func (s *Server) CountVideoType(_ context.Context, in *__.CountVideoTypeReq) (*__.CountVideoTypeResp, error) {
	var video model.Video
	videoType, _ := video.VideoType(config.DB, in.Keyword, in.TypeName, in.Sort, in.PayCount, in.Status, in.MemberStatus)
	var videolists []*__.CountVideoType
	for _, v := range videoType {
		list := &__.CountVideoType{
			Title:        v.Title,
			Dsc:          v.Dsc,
			TypeName:     v.TypeName,
			VideoId:      v.VideoId,
			CollectCount: v.CollectCount,
			PayCount:     v.PayCount,
			Hot:          v.Hot,
			CommentCount: v.CommentCount,
		}
		videolists = append(videolists, list)
	}
	result, _ := config.Rdb.Get(config.Ctx, "videolist").Result()
	if result != "" {
		json.Unmarshal([]byte(result), &in.Keyword)
	} else {
		marshal, _ := json.Marshal(&in.Keyword)
		config.Rdb.Set(config.Ctx, "videolist", marshal, time.Minute*10)
	}
	return &__.CountVideoTypeResp{
		List: videolists,
	}, nil
}
func (s *Server) CreateDram(_ context.Context, in *__.CreateDramReq) (*__.CreateDramResp, error) {
	dram := model.Dram{
		UserId:    in.UserId,
		Name:      in.Name,
		Dsc:       in.Dsc,
		DramCount: in.DramCount,
		DramTime:  in.DramTime,
	}
	err := config.DB.Create(&dram).Error
	if err != nil {
		return nil, err
	}
	return &__.CreateDramResp{
		DramId: int64(dram.ID),
	}, nil
}
func (s *Server) AppendAdd(_ context.Context, in *__.AppendAddReq) (*__.AppendAddResp, error) {
	appends := model.Append{
		UserId: in.UserId,
		DramId: in.DramId,
	}
	err := config.DB.Create(&appends).Error
	if err != nil {
		return nil, err
	}
	return &__.AppendAddResp{
		DramId: int64(appends.ID),
	}, nil
}
func (s *Server) CollectAdd(_ context.Context, in *__.CollectAddReq) (*__.CollectAddResp, error) {
	collect := model.CollectAdd{
		UserId:   in.UserId,
		DramId:   in.DramId,
		DramTime: in.DramTime,
	}
	err := config.DB.Create(&collect).Error
	if err != nil {
		return nil, err
	}
	return &__.CollectAddResp{
		CollectId: int64(collect.ID),
	}, nil
}
func (s *Server) RecordList(_ context.Context, in *__.RecordListReq) (*__.RecordListResp, error) {
	var record []model.Record
	config.DB.Where("records.name like ?", "%"+in.Keyword+"%").Order("created_at desc").Find(&record)
	var videolists []*__.RecordList
	for _, v := range record {
		list := &__.RecordList{
			UserId:       v.UserId,
			DramId:       v.DramId,
			DramTime:     v.DramTime,
			Name:         v.Name,
			MemberStatus: v.MemberStatus,
		}
		videolists = append(videolists, list)
	}
	return &__.RecordListResp{
		List: videolists,
	}, nil
}
func (s *Server) MemberOrder(_ context.Context, in *__.MemberOrderReq) (*__.MemberOrderResp, error) {
	var user model.User
	err := config.DB.Where("id=?", in.UserId).Find(&user).Error
	if err != nil {
		return nil, fmt.Errorf("用户不存在")
	}
	var drams model.Dram
	err = config.DB.Where("id=?", in.DramId).Find(&drams).Error
	if err != nil {
		return nil, fmt.Errorf("剧集不存在")
	}
	member := model.Member{
		UserId:      in.UserId,
		Price:       in.Price,
		MemberOrder: uuid.NewString(),
		DramId:      in.DramId,
	}
	config.DB.Create(&member)
	alipay := pkg.AliPays().Alipay(in.MemberOrder, strconv.FormatInt(in.Price, 10))
	log.Println(alipay)
	return &__.MemberOrderResp{
		PayUrl: alipay,
	}, nil
}
func (s *Server) MemberShow(_ context.Context, in *__.MemberShowReq) (*__.MemberShowResp, error) {
	var drams model.Dram
	err := config.DB.Where("id=?", in.DramId).Find(&drams).Error
	if err != nil {
		return nil, fmt.Errorf("剧集不存在")
	}
	if drams.MemberStatus == 1 {
		var user model.User
		err = config.DB.Where("id=?", in.UserId).Find(&user).Error
		if err != nil {
			return nil, fmt.Errorf("用户不存在")
		}
		if user.MemberStatus == 0 {
			return nil, fmt.Errorf("该剧集需要会员")
		}
	}
	return &__.MemberShowResp{
		Id:    int64(drams.ID),
		Title: drams.Name,
	}, nil
}
func (s *Server) VideoHotList(_ context.Context, in *__.VideoHotReq) (*__.VideoHotResp, error) {
	var videos []model.Video
	//一个月内的热度
	times := time.Now().AddDate(0, 0, -30)
	query := config.DB.Where("created_at>?", times)
	if in.Sort != 0 {
		query.Order("created_at desc")
	} else {
		query.Order("hot desc")
	}
	query.Find(&videos)
	var videolists []*__.VideoHot
	for _, v := range videos {
		list := &__.VideoHot{
			Title:        v.Title,
			Dsc:          v.Dsc,
			LikeCount:    v.LikeCount,
			CollectCount: v.CollectCount,
			PayCount:     v.PayCount,
			Hot:          v.Hot,
			CommentCount: v.CommentCount,
		}
		videolists = append(videolists, list)
	}
	marshal, err := json.Marshal(videolists)
	if err != nil {
		return nil, err
	}
	config.Rdb.Set(config.Ctx, "videolists", marshal, time.Minute*10)
	return &__.VideoHotResp{
		List: videolists,
	}, nil
}
